﻿//-----------------------------------------------------------------------
// <copyright file="AddColumn.aspx.cs" company="Microsoft Corporation">
// Copyright (c) Microsoft Corporation.
// All rights reserved.
// THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY 
// KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
// PARTICULAR PURPOSE.
// This code released under the terms of the 
// Microsoft Public License (MS-PL, http://opensource.org/licenses/ms-pl.html.)
// </copyright>
// <author>Medha</author>
// <date>16-May-2011</date>
//-----------------------------------------------------------------------

namespace SmartTag.Layouts
{
    using System;
    using System.Security.Permissions;
    using System.Web;
    using System.Web.UI.WebControls;
    using Microsoft.SharePoint;
    using Microsoft.SharePoint.ApplicationPages;
    using Microsoft.SharePoint.Taxonomy;
    using Microsoft.SharePoint.Utilities;
    using SmartTag.Common.Utility;
    using SmartTag.Configuration;

    /// <summary>
    /// AddColumn page to add a managed metadata column in configuration
    /// </summary>
    public partial class AddColumn : ListPageBase
    {
        /// <summary>
        /// Document Library Id
        /// </summary>
        private string listId;

        /// <summary>
        /// Flag to check if list contatins taxonomy field which is unconfigured 
        /// </summary>
        private bool taxFieldFound;

        /// <summary>
        /// Handles the Load event of the Page control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void Page_Load(object sender, EventArgs e)
        {
            this.listId = "{" + this.List.ID.ToString() + "}";

            if (!IsPostBack)
            {
                this.Initialize();
            }
        }

        /// <summary>
        /// Creates the child controls on the <see cref="T:Microsoft.SharePoint.WebControls.UnsecuredLayoutsPageBase"/>.
        /// </summary>
        [PermissionSet(SecurityAction.LinkDemand, Name = "FullTrust")]
        protected override void CreateChildControls()
        {
            // Add event handlers
            this.btnOk.Click += new EventHandler(this.BtnOk_Click);
            this.btnCancel.Click += new EventHandler(this.BtnCancel_Click);
            base.CreateChildControls();
        }

        /// <summary>
        /// Handles the Click event of the BtnOk control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void BtnOk_Click(object sender, EventArgs e)
        {
            this.SaveConfiguration();
            SPUtility.Redirect(SPHttpUtility.UrlPathEncode(string.Format("SmartTag/Configuration.aspx?List={0}", this.listId), true), SPRedirectFlags.RelativeToLayoutsPage, HttpContext.Current);
        }

        /// <summary>
        /// Handles the Click event of the BtnCancel control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void BtnCancel_Click(object sender, EventArgs e)
        {
            SPUtility.Redirect(SPHttpUtility.UrlPathEncode(string.Format("SmartTag/Configuration.aspx?List={0}", this.listId), true), SPRedirectFlags.RelativeToLayoutsPage, HttpContext.Current);
        }

        /// <summary>
        /// Initializes this instance.
        /// </summary>
        private void Initialize()
        {
            this.InitializeUI();
        }

        /// <summary>
        /// Initializes the UI.
        /// </summary>
        private void InitializeUI()
        {
            try
            {
                /* Load the configuration */
                DocumentLibraryConfiguration config = ConfigurationHelper.LoadConfiguration(this.List);

                foreach (SPField field in this.List.Fields)
                {
                    TaxonomyField taxField = field as TaxonomyField;
                    if (taxField != null && taxField.TypeAsString.Equals("TaxonomyFieldTypeMulti", StringComparison.OrdinalIgnoreCase))
                    {
                        string fieldId = string.Format("{{{0}}}", taxField.Id.ToString());
                        /* Now check if the column is already there */
                        ColumnConfiguration columnConfig =
                        config.ColumnConfiguration.Find(new Predicate<ColumnConfiguration>(delegate(ColumnConfiguration colConfig)
                        {
                            if (fieldId.Equals(colConfig.ColumnId, StringComparison.OrdinalIgnoreCase))
                            {
                                return true;
                            }

                            return false;
                        }));

                        if (columnConfig != null)
                        {
                            continue;
                        }

                        /* Set the flag */
                        this.taxFieldFound = true;

                        ListItem listItem = new ListItem();
                        listItem.Text = taxField.Title;
                        listItem.Value = fieldId;
                        this.ddlManagedMetadataColumns.Items.Add(listItem);
                    }
                }

                // Check if we have any taxonomy field unconfigured if not, Clear UI and display message
                this.InitializeUI(this.taxFieldFound);
            }
            catch (Exception ex)
            {
                Logger.LogError(ex, "Error occured in FillManagedMetadataColumnsDdl in AddColumn.aspx", (int)TraceLogEventId.FillManagedMetadataColumnsDdl);
            }
        }

        /// <summary>
        /// Initializes the UI.
        /// </summary>
        /// <param name="taxFieldFound">if set to <c>true</c> [tax field found].</param>
        private void InitializeUI(bool taxFieldFound)
        {
            if (taxFieldFound)
            {
                return;
            }

            // Disable controls
            this.ddlManagedMetadataColumns.Enabled = false;
            this.txtNumberOfWords.Enabled = false;
            this.txtRelevance.Enabled = false;
            this.btnOk.Enabled = false;

            // Display alert
            Page.ClientScript.RegisterStartupScript(
                this.GetType(),
                "AlertNoColumnsFound",
                "<script type=\"text/javascript\">AlertColumnsFound();</script>");
        }

        /// <summary>
        /// Saves the configuration.
        /// </summary>
        private void SaveConfiguration()
        {
            try
            {
                string fieldId = this.ddlManagedMetadataColumns.SelectedValue;
                SPField field = this.List.Fields[new Guid(fieldId)];

                DocumentLibraryConfiguration config = ConfigurationHelper.LoadConfiguration(this.List);

                /* Now check if the column is already there */
                ColumnConfiguration columnConfig =
                config.ColumnConfiguration.Find(new Predicate<ColumnConfiguration>(delegate(ColumnConfiguration colConfig)
                {
                    if (fieldId.Equals(colConfig.ColumnId, StringComparison.OrdinalIgnoreCase))
                    {
                        return true;
                    }

                    return false;
                }));

                if (columnConfig == null)
                {
                    columnConfig = new ColumnConfiguration();
                    config.ColumnConfiguration.Add(columnConfig);
                }

                columnConfig.ColumnId = fieldId;
                columnConfig.ColumnName = field.Title;
                columnConfig.WordsToScan = int.Parse(this.txtNumberOfWords.Text);
                columnConfig.Relevance = int.Parse(this.txtRelevance.Text);

                ConfigurationHelper.SaveConfiguration(this.List, config);
            }
            catch (Exception ex)
            {
                Logger.LogError(ex, "Error occured in SaveConfiguration in AddColumn.aspx", (int)TraceLogEventId.SaveConfiguration);
            }
        }
    }
}
